$(document).ready(function() {
    $("#upload-progress").progressbar();
    
    var uploader = getUploader('add_file', 'wrap_upload_buttons');

    uploader.init();
    
    uploader.bind("BeforeUpload", function(up, file) {
        $("#upload-progress").css("display", "block");
    });

    uploader.bind("FilesAdded", function(up, file){
        uploader.start();
    });

    uploader.bind('FileUploaded', function(up, files, resp) {
        var result = $.parseJSON(resp.response);
        
        var file_name = result.file_name;
        var splits = file_name.split(".");
        var file_extension = splits[splits.length - 1];
        var file_type = 'word';
        switch (file_extension) {
            case 'jpg': 
            case 'png':
            case 'gif':
                file_type = 'bmp';
                break;
            case 'xlsx':
            case 'xls':
                file_type = 'excel';
                break;
            case 'pdf': 
                file_type = 'pdf';
                break;
        }
        var file_path = result.path;
        
        var content = '<div class="' + file_type + ' file-new">';
        content += '<span>';
        content += file_name;
        content += '</span>';
        content += "<input type='hidden' name='documents[]' value='" + file_path + "'/>";
        content += " <a href='javascript:void(0)' class='delete-file' onclick='deleteUploadFile(event, \"" + file_path + "\")'>";
        content += "<img src='" + base_url + "/public/images/delete.gif'>";
        content += "</a>";
        content += '</div>';

        $("#mask-new-file").append(content);
        $(".ui-progressbar").css("display", "none");
    });

    uploader.bind('UploadProgress', function(up, file) {
        $("#upload-progress").progressbar({
            value: file.percent
        });
    });

    $('#start_upload').click(function() {
        uploader.start();
        return false;
    });  
    $("#confirm_dialog").dialog({
        modal: true,
        autoOpen: false,
        resizable: false,
        draggable: false,
        position: ["center", "top"]
    })
    
    $(".final_dunnage_usage").keypress(function(event) {
        var value = $( this ).val();
        var c = String.fromCharCode(event.which);
        if ( !$.isNumeric(value + c) ) {
            event.preventDefault();
        } else {
            var price_per_unit = $( this ).parent().siblings(".price").text();
            price_per_unit = parseInt(price_per_unit);
            var final_dunnage_cost = parseInt(value + c) * price_per_unit;
            $( this ).parent().siblings(".FDC").children("input").val(final_dunnage_cost);
            calculateTotal();
        }
    });
    
    $(".estimated_dunnage_usage").keypress(function(event) {
        var value = $( this ).val();
        var c = String.fromCharCode(event.which);
        if ( !$.isNumeric(value + c) ) {
            event.preventDefault();
        } else {
            var price_per_unit = $( this ).parent().siblings(".price").text();
            price_per_unit = parseInt(price_per_unit);
            var final_dunnage_cost = parseInt(value + c) * price_per_unit;
            $( this ).parent().siblings(".EDC").children("input").val(final_dunnage_cost);
            calculateTotal();
        }
    });
});

function deleteUpdateDunnageOperation(id) {
    $("#confirm_dialog").dialog("open");
    $("#confirm_dialog").dialog({
        buttons: {
            "Yes": function() {
                $.post(base_url + "/service/delete-update-dunnage-operation", {id : id}, function(resp) {
                    $("#tr_" + id).remove();
                });
                $(this).dialog( "close" );
            },
            "No": function() {
                $(this).dialog( "close" );
            }
        }
    });
}

function calculateTotal() {
    var final_dunnage_cost = 0;
    $(".final_dunnage_cost").each(function() {
        if ( $(this).val() ) {
            final_dunnage_cost += parseInt($( this ).val());    
        }
    });
    if ( final_dunnage_cost === 0 ) {
        var estimated_dunnage_cost = 0;
        $(".estimated_dunnage_cost").each(function() {
            console.log($(this).val());
            if ( $(this).val() ) {
                estimated_dunnage_cost += parseInt($(this).val());
            }
        });
        $("#totalval").val(estimated_dunnage_cost);
    } else {
        $("#totalval").val(final_dunnage_cost);
    }
}
